<template>
  <div class="header-title">
    <SvgIcon :size="18" name="fa fa-solid fa-spider" class="title-icon"></SvgIcon>
    <el-text @click="handleFocus">
      工作空间 -
      <el-button size="small" v-show="!focus">
        <span class="title">
          {{ comTitle }}
        </span>
      </el-button>
    </el-text>

    <el-input v-show="focus" ref="inputInstRef" size="small" type="text" maxlength="16" show-word-limit
      class="title-input" placeholder="请输入项目名称" v-model:value.trim="title" @keyup.enter="handleBlur"
      @blur="handleBlur"></el-input>
  </div>
</template>
<script lang="ts" setup>
import { ref, nextTick, computed } from 'vue'
import { fetchRouteParamsLocation, setTitle } from '@/utils'
import { useChartEditStore } from '@/stores/modules/chartEditStore/chartEditStore'
import { EditCanvasConfigEnum } from '@/stores/modules/chartEditStore/chartEditStore.d'

const chartEditStore = useChartEditStore()

const focus = ref<boolean>(false)
const inputInstRef = ref(null)

// 根据路由 id 参数获取项目信息
const fetchProhectInfoById = () => {
  const id = fetchRouteParamsLocation()
  if (id.length) {
    return id[0]
  }
  return ''
}

const title = ref<string>(fetchProhectInfoById() || '')

const comTitle = computed(() => {
  // eslint-disable-next-line vue/no-side-effects-in-computed-properties
  title.value = title.value.replace(/\s/g, '')
  const newTitle = title.value.length ? title.value : '新项目'
  setTitle(`工作空间-${newTitle}`)
  chartEditStore.setEditCanvasConfig(EditCanvasConfigEnum.PROJECT_NAME, newTitle)
  return newTitle
})

const handleFocus = () => {
  focus.value = true
  nextTick(() => {
    inputInstRef.value && (inputInstRef.value as any).focus()
  })
}

const handleBlur = () => {
  focus.value = false
}
</script>
<style lang="scss" scoped>
.header-title {
  color: var(--el-text-color-regular);
  display: flex;
  justify-content: center;
  align-items: center;

  .title-icon{
    color: var(--el-text-color-secondary);
    margin-right: 12px;
  }

  .title-input {
    width: 200px;
    margin-left: 8px;
  }
}
</style>